jihyeon's Blog

2023-11-14

효율적인 해킹


https://www.acmicpc.net/problem/1325

어떤 노드가 간선으로 가장 많이 연결되어 있는지 구하는 문제

모든 노드에 대해 순회를 실행하여 연결된 노드 개수를 구함(반복문에서 count+1) 모든 노드를 순회하기 위한 반복문을 돌릴 때 얻은 count로 결과 도출

from collections import deque def bfs(v): q = deque([v]) visited = [False] * (n + 1) visited[v] = True count = 1 while q: v = q.popleft() for e in adj[v]: if not visited[e]: q.append(e) visited[e] = True count += 1 return count n, m = map(int, input().split()) adj = [[] for _ in range(n + 1)] for _ in range(m): x, y = map(int, input().split()) adj[y].append(x) # 순회하면서 얻은 간선 개수 중 가장 많은 걸 출력 result = [] max_value = -1 for i in range(1, n + 1): c = bfs(i) if c > max_value: result = [i] max_value = c elif c == max_value: result.append(i) for e in result: print(e, end=" ")

Copyright (c) 2023. jihyeon Choi. | All Right Reserved.